package site.lanmushan.framework.authorization.strategy.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import site.lanmushan.framework.authorization.Authority;
import site.lanmushan.framework.authorization.strategy.ContextStorageStrategy;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author Administrator
 */
@Slf4j
public class LocalContextStorageStrategy implements ContextStorageStrategy {
    /**
     * 存储器
     */
    Map<String, Authority> storageMap = new ConcurrentHashMap<>();
    /**
     * 正则匹配的
     */
    List<Authority> matcherAuthorityList = new CopyOnWriteArrayList<>();
    final PathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public Authority getPermissionAuthorityByKey(String key) {
        return storageMap.get(key);
    }

    @Override
    public List<Authority> getAllPermissionAuthority() {
        return null;
    }

    @Override
    public List<Authority> getMatcherPermissionAuthority() {
        return matcherAuthorityList;
    }

    @Override
    public void savePermissionAuthority(List<Authority> authorities) {
        List<Authority> tempList = new ArrayList<>();
        for (Authority authority : authorities) {
            if (!pathMatcher.isPattern(authority.getUrl())) {
                storageMap.put(authority.getUrl(), authority);
            } else {
                tempList.add(authority);
            }
        }
        matcherAuthorityList.addAll(tempList);
        log.info("权限存储成功-->指定URL数量:{}", storageMap.size());
        log.info("权限存储成功-->正则URL数量:{}", matcherAuthorityList.size());

    }

    @Override
    public void removePermissionAuthority(String key) {

    }

    @Override
    public synchronized void clean() {
        storageMap.clear();
        ;
        matcherAuthorityList.clear();
    }
}
